<?php


namespace app\admin\controller;


use app\admin\model\FlowInstance;
use app\admin\model\FlowTask;
use app\BaseController;
use think\Exception;
use think\facade\Db;
use think\facade\View;
use think\Request;
use function fast\e;

class Start extends BaseController
{
    /**
     * Scheme模型对象
     * @var \app\admin\model\flow\Scheme
     */
    protected $model = null;
    protected $noNeedRight = ['*'];
    protected $runtime = null;
    protected $searchFields = 'id,flowcode,flowname';
    protected $instance = null;
    protected $currentNode = null;
    protected $stepid = null;
    protected $nextNode = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Scheme();
        $this->instance = new FlowInstance();
    }

    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $result = \app\admin\model\Scheme::paginate($limit, false, ['page' => $page])->toArray();
            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }

        return View::fetch();
    }


    public function edit(Request $request)
    {
        if ($request->isAjax()) {
            $id = $request->param('id');
            $scheme = \app\admin\model\Scheme::find($id);
            if (!$scheme) {
                throw new Exception('流程不存在');
            }
            $data = [
                'instancecode' => 'QJ20200700065',
                'start_time' => '2020-07-10 11:24:32',
                'end_time' => '2020-07-10 11:24:32',
                'content' => '请假',
                'day' => "1"
            ];
            $instanceid = \fast\Random::uuid();
            $bizobjectid = \fast\Random::uuid();
            $ids['instanceid'] = $instanceid;
            $ids['bizobjectid'] = $bizobjectid;
            $flowTmp = $scheme; //当前任务
            $originator = $this->auth->id; //当前用户
            $instancecode = '';
            if (array_key_exists('instancecode', $data)) {
                $instancecode = $data['instancecode'];
                unset($data['instancecode']);
            } else {
                $instancecode = time();
            }
            $instance = new FlowInstance();
//            //新建流程实例
            $instance->save([
                'id' => $instanceid,
                'originator' => $originator,
                'scheme' => $flowTmp['id'],
                'createtime' => date("Y-m-d h:i:s"),
                'instancecode' => $instancecode,
                'bizobjectid' => $bizobjectid,
                'instancestatus' => 1
            ]);
            $content = json_decode($flowTmp->flowcontent, true);
            //所有连线信息
            $lines = $content['lines'];

            //所有节点信息
            $nodes = $content['nodes'];
            $rtnNext = null;
            $nextNodeIndex = null;
            //如果是开始节点需要保存开始数据和下一个节点的代办数据
            $rtn = array_search('start', array_column($nodes, 'type'));
            $this->currentNode = $nodes[$rtn];
            $this->stepid = $this->currentNode['id'];
            $task = new FlowTask();
            $task->save([
                'id' => \fast\Random::uuid(),
                'flowid' => $flowTmp['id'],
                'stepname' => $this->currentNode['name'],
                'stepid' => $this->currentNode['id'],
                'receiveid' => $this->auth->id, //审批人
                'instanceid' => $instanceid,
                'senderid' => $this->auth->id, //上一步审核人
                'status' => '2',
                'createtime' => date("Y-m-d H:i:s"),
                'completedtime' => date("Y-m-d H:i:s"),
                'comment' => '提交'
            ]);
            $nextNodeArray = array_filter($lines, function ($t) {
                return $t['from'] == $this->stepid;
            });
            $all = count($nextNodeArray);

            $normal = 0;
            foreach ($nextNodeArray as $line) {
                if (array_key_exists('setInfo', $line['data'])) {
                    try {

                        $express = $line['data']['setInfo']['express'] == '' ? '1=1' : $line['data']['setInfo']['express'];
                        $sql = "select * from (select * from " . $flowTmp->bizscheme . " where id = '" . $bizobjectid . "') a where  " . $express;
                        $table = Db::query($sql);
                        if (count($table) < 1) {
                            $normal++;
                            continue;
                        }
                    } catch (Exception $e) {
                        continue;
                        throw new Exception('流程条件异常,请联系管理员');
                    }
                }
                if ($normal == $all) {
//                    Db::name('admin_log')->insert([
//                        'admin_id' => $this->admin['id'], 'url' => '', 'title' => '流程异常', 'content' => '流程无法找到下一个节点'
//                    ]);
                    throw new Exception('流程无法找到下一个节点');
                }
                //find node where id is line's id
                $this->nextNode = array_filter($nodes, function ($t) use ($line) {
                    return $t['id'] == $line['to'];
                });
                $this->nextNode = array_values($this->nextNode)[0];
                $stepName = $this->nextNode['name'];
                if ($stepName == "结束") {
                    if (count($nextNodeArray) == 1 && $this->nextNode['name'] == '结束') {
                        //更改当前实例为结束
                        $instance->where('id', $instanceid)->update(['instancestatus' => 2, 'completedtime' => date("Y-m-d H:i:s")]);
                        //插入结束节点task
                        Db::name("flow_task")->insert([
                            'id' => \fast\Random::uuid(),
                            'flowid' => $flowTmp['id'],
                            'stepname' => $this->nextNode['name'],
                            'stepid' => $this->nextNode['id'],
                            'receiveid' => '',
                            'instanceid' => $instanceid,
                            'senderid' => $this->auth->id,
                            'status' => '2',
                            'createtime' => date("Y-m-d H:i:s"),
                            'completedtime' => date("Y-m-d H:i:s"),
                            'comment' => '结束'
                        ]);
                    }
                    break;
                }
                $nodeType = $this->nextNode['setInfo']['nodeDesignate'];
                $dataset = [];
                $userList = [];
                if ($nodeType == "user") { //用户
                    if (is_array($this->nextNode['setInfo']['NodeDesignateData']['users'])) {
                        $userList = $this->nextNode['setInfo']['NodeDesignateData']['users'];
                    } else {
                        $userList = strlen($this->nextNode['setInfo']['NodeDesignateData']['users']) > 0 ? explode(',', $this->nextNode['setInfo']['NodeDesignateData']['users']) : [];
                    }
                    foreach ($userList as $user) {
                        $dataset[] = [
                            'id' => \fast\Random::uuid(),
                            'flowid' => $flowTmp['id'],
                            'stepname' => $this->nextNode['name'],
                            'stepid' => $this->nextNode['id'],
                            'receiveid' => $user,
                            'instanceid' => $instanceid,
                            'senderid' => $this->auth->id,
                            'status' => '0',
                            'createtime' => date("Y-m-d H:i:s")
                        ];
                    }
                }
                if ($nodeType == 'dept') { //上级领导
                    $userList = $this->getdeptmanager($originator);
                    foreach ($userList as $user => $v) {
                        $dataset[] = [
                            'id' => \fast\Random::uuid(),
                            'flowid' => $flowTmp['id'],
                            'stepname' => $this->nextNode['name'],
                            'stepid' => $this->nextNode['id'],
                            'receiveid' => $v['manager'],
                            'instanceid' => $instanceid,
                            'senderid' => $this->auth->id,
                            'status' => '0',
                            'createtime' => date("Y-m-d H:i:s")
                        ];
                    }
                }
                if ($nodeType == 'role') { //角色
                    $role = '';
                    if (is_array($this->nextNode['setInfo']['NodeDesignateData']['role'])) {
                        $role = $this->nextNode['setInfo']['NodeDesignateData']['role'];
                        if (!$role) {
                            throw new Exception('找不到角色');
                        } else {
                            $role = $role[0];
                        }
                    } else {
                        $role = $this->nextNode['setInfo']['NodeDesignateData']['role'];
                    }
                    $userList = $this->getuserbyrole($role);
                    foreach ($userList as $user => $v) {
                        $dataset[] = [
                            'id' => \fast\Random::uuid(),
                            'flowid' => $flowTmp['id'],
                            'stepname' => $this->nextNode['name'],
                            'stepid' => $this->nextNode['id'],
                            'receiveid' => $v['id'],
                            'instanceid' => $instanceid,
                            'senderid' => $this->auth->id,
                            'status' => '0',
                            'createtime' => date("Y-m-d H:i:s")
                        ];
                    }
                }

                if (count($userList) == 0) {
                    $dataset[] = [
                        'id' => \fast\Random::uuid(),
                        'flowid' => $flowTmp['id'],
                        'stepname' => $this->nextNode['name'],
                        'stepid' => $this->nextNode['id'],
                        'receiveid' => '',
                        'instanceid' => $instanceid,
                        'senderid' => $this->auth->id,
                        'status' => '0',
                        'createtime' => date("Y-m-d H:i:s")
                    ];
//                    Db::name('flow_mail')->insert([
//                        'subject' => '无审批人',
//                        'content' => '实例id' . $instanceid . ' 无审批人请及时处理',
//                        'createdtime' => date('Y-m-d H:i:s'),
//                        'issend' => '0',
//                        'senddate' => '0000-00-00 00:00:00',
//                        'address' => $this->getemail($flowTmp->flowcanuser),
//                        'message' => ''
//                    ]);
                };
                $task->saveAll($dataset, false);
            }
            $params = $data;
            $params['id'] = $bizobjectid;
            if ($data) {
                Db::table($flowTmp['bizscheme'])->insert($params);
            }
        }
    }

    /**根据角色获取用户
     * @param $role
     * @return mixed
     */
    public function getuserbyrole($role)
    {
        $sql = "SELECT a.id FROM admins a 
                LEFT JOIN auth_group_access b ON a.id = b.uid
                LEFT JOIN auth_group c ON b.group_id=c.id
                WHERE c.`id`='" . $role . "'";
        $user = Db::query($sql);
        return $user;
    }

    /**
     * 获取发起人当前部门负责人
     */
    public function getdeptmanager($originator)
    {
        $sql = "select manager from admins a 
               left join flow_department b on a.department_id=b.id where a.id=" . $originator;
        $user = Db::query($sql);
        return $user;
    }

}